home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
SuperHack
/
SuperHack CD.bin
/
Hack
/
UNIX
/
FSORT_C.ZIP
/
FSORT_C
Wrap
Text File
|
1996-06-23
|
3KB
|
168 lines
/* fsort.c -- sort files according to depth.
*
* Read a list of files from stdin and sort them so that most shallow
* filenames come first. That is, given the list of files
*
* a/b
* a
* a/b/c/d
* a/b/c
*
* this program will output
*
* a
* a/b
* a/b/c
* a/b/c/d
*
* No other sorting is done (e.g. alphabetic). Sorting is done based
* purely on the number of `/' characters in each pathname.
* It is easy enough to change the sorting criteria by changing the
* definition of qcmp below.
* WARNING: Since this program uses quicksort, it does not sort stably.
*/
#include <stdio.h>
char *malloc ();
char *strchr ();
int qcmp ();
char *xmalloc ();
struct node
{
char *str;
struct node *next;
};
int
main (argc, argv)
int argc;
char **argv;
{
struct node root, *p, *q;
char l[255], **s, *newline;
int t, i;
p = q = &root;
p->str = NULL;
p->next = NULL;
t = 0;
while (fgets (l, 254, stdin))
{
if (newline = strchr (l, '\n'))
*newline = '\0';
q = (struct node *) xmalloc (sizeof (struct node));
q->str = (char *) xmalloc ((strlen (l) + 1) * sizeof (char));
strcpy (q->str, l);
q->next = NULL;
p->next = q;
p = q;
t++;
}
p = &root;
s = (char **) xmalloc (t * sizeof (char *));
i = 0;
while (p = p->next)
s[i++] = p->str;
qs_sort (s, t, qcmp);
for (i = 0; i < t; i++)
puts (s[i]);
return 0;
}
int
qcmp (a, b)
char *a, *b;
{
int an, bn;
char *s;
an = bn = 0;
while (s = strchr (a, '/'))
{
an++;
a = s + 1;
}
while (s = strchr (b, '/'))
{
bn++;
b = s + 1;
}
if (an < bn)
return -1;
if (an > bn)
return 1;
return 0;
}
char *
xmalloc (size)
int size;
{
char *message = "xmalloc: out of memory.\n";
char *p;
p = (char *) malloc (size);
if (p == NULL)
{
write (2, message, sizeof (message));
exit (1);
}
return p;
}
qs_sort (base, count, func)
char *base[];
int count;
int (*func) ();
{
qs_internal (base, 0, count - 1, func);
}
qs_internal (base, left, right, func)
char *base[];
int left, right;
int (*func) ();
{
int i, j;
char *x, *y;
i = left;
j = right;
x = base[(left + right)/2];
do
{
while ((*func) (base[i], x) < 0 && i < right) i++;
while ((*func) (base[j], x) > 0 && j > left) j--;
if (i <= j)
{
y = base[i];
base[i] = base[j];
base[j] = y;
i++;
j--;
}
}
while (i <= j);
if (left < j)
qs_internal (base, left, j, func);
if (i < right)
qs_internal (base, i, right, func);
}